package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.Destination;
import cn.wolfcode.wolf2w.business.api.domain.Region;
import cn.wolfcode.wolf2w.business.mapper.DestinationMapper;
import cn.wolfcode.wolf2w.business.mapper.RegionMapper;
import cn.wolfcode.wolf2w.business.query.DestinationQuery;
import cn.wolfcode.wolf2w.business.service.IDestinationService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 目的地Service业务层处理
 * 
 * @author hnz
 * @date 2025-09-16
 */
@Service
@Transactional
public class DestinationServiceImpl extends ServiceImpl<DestinationMapper,Destination> implements IDestinationService {

    @Autowired
    private RegionMapper regionMapper;
    @Override
    public IPage<Destination> queryPage(DestinationQuery qo) {
        IPage<Destination> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        return lambdaQuery()
                .page(page);
    }

    @Override
    public List<Destination> queryByRegionId(Long regionId) {

        List<Destination> list=null;
        if (regionId==-1){
            list = lambdaQuery().eq(Destination::getParentId, 1) .list();
        }else {
            Region region = regionMapper.selectById(regionId);
            String refIds = region.getRefIds();
            String[] split = refIds.split(",");
            list=new ArrayList<>();
            for (String string : split) {
                Long id = Long.valueOf(string);
                Destination destination = baseMapper.selectById(id);
                list.add(destination);
            }
        }
        //查询2级数据
        for (Destination destination : list){
            List<Destination> secondLevel = lambdaQuery().eq(Destination::getParentId, destination.getId())
                    .last("limit 10").list();
            destination.setChildren(secondLevel);

        }
        return list;
    }

    @Override
    public List<Destination> queryToasts(Long destId) {
        List<Destination> list = new ArrayList<>();
        createToasts(destId,list);
//        Collections.reverse(list);

        return list;
    }
    private void createToasts(Long destId,List<Destination> list){
        if (destId==null){
            return;
        }
        Destination destination = baseMapper.selectById(destId);
        createToasts(destination.getParentId(),list);
        list.add(destination);


    }
}
